    package cn.gok.project.util;

    import cn.hutool.json.JSONObject;
    import org.springframework.cloud.gateway.filter.GatewayFilterChain;
    import org.springframework.cloud.gateway.filter.GlobalFilter;
    import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
    import org.springframework.core.Ordered;
    import org.springframework.core.io.buffer.DataBuffer;
    import org.springframework.core.io.buffer.DataBufferFactory;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Component;
    import org.springframework.web.server.ServerWebExchange;
    import reactor.core.publisher.Mono;

    import java.nio.charset.StandardCharsets;

    @Component
    public class AuthGlobalFilter implements GlobalFilter, Ordered {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            // 1. 获取请求头中的Token
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");
            JSONObject json = new JSONObject();
            json.put("code", 401);
            json.put("msg", "校验不通过");



            // 2. 校验Token：若不存在，返回401未授权
            if (token == null || token.isEmpty()) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 设置响应状态码
    //            exchange.getResponse().getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                // 向响应体中写入"未授权"信息并结束请求
                // 将JSON转换为DataBuffer
                DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
                DataBuffer buffer = bufferFactory.wrap(
                        json.toString().getBytes(StandardCharsets.UTF_8)
                );

                // 写入响应体并返回
                return exchange.getResponse().writeWith(Mono.just(buffer));
            }

            // 3. Token存在，继续执行过滤器链（放行）
            return chain.filter(exchange);
        }

        // 定义执行顺序：需在路由转发前执行（值小于NettyWriteResponseFilter的ORDER）
        @Override
        public int getOrder() {
            return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
        }
    }